<template>
  <div class="banner-add-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>添加轮播图</span>
          <el-button @click="goBack">返回列表</el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        v-loading="loading"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入轮播图标题" />
        </el-form-item>

        <el-form-item label="图片" prop="image_url">
          <el-upload
            class="avatar-uploader"
            :action="`${BASE_URL}/user/upload_file`"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
          >
            <img
              v-if="form.image_url"
              :src="form.image_url"
              class="avatar"
              @click.stop="previewImage"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">建议尺寸：750x350像素，JPG/PNG格式</div>
        </el-form-item>

        <el-form-item label="链接地址" prop="link_url">
          <el-input v-model="form.link_url" placeholder="请输入链接地址" />
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="form.sort"
            :min="0"
            :max="99"
            controls-position="right"
          />
          <span class="tip-text">数字越小越靠前</span>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">显示</el-radio>
            <el-radio :label="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 图片预览组件 -->
    <el-image
      style="display: none"
      :src="form.image_url"
      :preview-src-list="form.image_url ? [form.image_url] : []"
      :initial-index="0"
      ref="imageRef"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { addBanner } from "@/api/banners";

import { BASE_URL } from "@/config";

const router = useRouter();
const formRef = ref(null);
const imageRef = ref(null);
const loading = ref(false);

// 表单数据
const form = reactive({
  title: "",
  image_url: "",
  link_url: "",
  sort: 0,
  status: 1,
});

// 表单验证规则
const rules = reactive({
  title: [
    { required: true, message: "请输入轮播图标题", trigger: "blur" },
    { max: 50, message: "长度不能超过50个字符", trigger: "blur" },
  ],
  image_url: [
    { required: true, message: "请上传轮播图图片", trigger: "change" },
  ],
  link_url: [{ required: true, message: "请输入链接地址", trigger: "blur" }],
});

// 上传相关配置
const uploadHeaders = {
  Authorization: `Bearer ${localStorage.getItem("token")}`,
};

// 返回列表页
const goBack = () => {
  router.push("/banner/list");
};

// 上传前验证
const beforeUpload = (file) => {
  const isJPG = file.type === "image/jpeg";
  const isPNG = file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 5;

  if (!isJPG && !isPNG) {
    ElMessage.error("上传图片只能是 JPG 或 PNG 格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("上传图片大小不能超过 2MB!");
    return false;
  }
  return true;
};

// 上传成功回调
const handleUploadSuccess = (res) => {
  if (res.code === 1) {
    form.image_url = res.url;
    form.link_url = res.url;
    ElMessage.success("上传成功");
  } else {
    ElMessage.error(res.message || "上传失败");
  }
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid) => {
    if (!valid) return;

    loading.value = true;
    try {
      const res = await addBanner(form);
      if (res.code === 0) {
        ElMessage.success("添加成功");
        goBack();
      } else {
        ElMessage.error(res.message || "添加失败");
      }
    } catch (error) {
      console.error("添加失败", error);
      ElMessage.error("添加失败");
    } finally {
      loading.value = false;
    }
  });
};

// 预览图片
const previewImage = (e) => {
  e.stopPropagation();
  if (imageRef.value) {
    imageRef.value.clickHandler();
  }
};
</script>

<style scoped>
.banner-add-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.tip-text {
  margin-left: 10px;
  color: #999;
  font-size: 12px;
}
.avatar-uploader {
  width: 360px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 360px;
  height: 180px;
  text-align: center;
  line-height: 180px;
}
.avatar {
  width: 360px;
  height: 180px;
  display: block;
}
.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

/* 修复图片预览z-index问题 */
:deep(.el-image-viewer__wrapper) {
  z-index: 2100 !important; /* 确保图片预览在最上层 */
}

/* 增强图片预览遮罩层效果 */
:deep(.el-image-viewer__mask) {
  z-index: 2099 !important; /* 确保遮罩层在高层级 */
  opacity: 0.9 !important; /* 增加不透明度 */
  pointer-events: auto !important; /* 确保遮罩层可以接收鼠标事件 */
}
</style>
